package com.example.demospringboot.netty.http.handler;

import com.google.common.net.HttpHeaders;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenlei
 * @date 2020-01-07
 * todo 服务端请求接收以及返回的处理器
 *  todo 处理传过来的参数可以封装成一个bean,必传参数为service的beanName，以及需要执行method
 *  todo 调用方法返回
 **/
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> implements ApplicationContextAware {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /*
     * @author chenlei
     * @date 2020-01-07
     * @description
     * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object)
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        // TODO Auto-generated method stub
        String uri = req.uri();
        System.out.println(uri);
        logger.info("报文体"+req.content().toString(CharsetUtil.UTF_8));
        Map<String, String> result = new HashMap<>();
        result.put("method", req.method().name());
        result.put("uri", uri);
        String msg = "<html><head><title>test</title></head><body>你请求uri为：" + uri + "</body></html>";
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1
                , HttpResponseStatus.OK,
                Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaders.CONTENT_TYPE, "text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

}
